<!-- ProductAdd.vue -->
<template>
  <div class="product-add-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="page-header">
      <el-page-header @back="goBack" content="添加商品"></el-page-header>
    </div>

    <el-card class="form-card">
      <el-form
        label-width="100px"
        label-position="top"
        class="product-form"
        ref="productFormRef"
        :model="productForm"
        :rules="formRules">

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品名称" prop="productName">
              <el-input
                placeholder="请输入商品名称"
                v-model="productForm.productName">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所需积分" prop="pointsRequired">
              <el-input-number
                v-model="productForm.pointsRequired"
                :min="0"
                placeholder="请输入所需积分"
                style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存数量" prop="quantity">
              <el-input-number
                v-model="productForm.quantity"
                :min="0"
                placeholder="请输入库存数量"
                style="width: 100%;">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品图片" prop="imageUrl">
              <el-upload
                class="product-uploader"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :show-file-list="false"
                :on-success="handleImageSuccess"
                :on-error="handleImageError"
                :before-upload="beforeImageUpload"
                :disabled="uploading">
                <img v-if="productForm.imageUrl" :src="getImageUrl(productForm.imageUrl)" class="product-image-preview">
                <el-icon v-else class="product-uploader-icon"><Plus /></el-icon>
                <div class="upload-text" v-if="!productForm.imageUrl">点击上传图片</div>
              </el-upload>
              <div class="image-url-display" v-if="productForm.imageUrl">
                <el-input
                  v-model="productForm.imageUrl"
                  readonly
                  class="image-url-input">
                  <template #append>
                    <el-button @click="productForm.imageUrl = ''">清除</el-button>
                  </template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述1" prop="description1">
              <el-input
                type="textarea"
                placeholder="请输入商品描述1"
                v-model="productForm.description1"
                :rows="3">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述2" prop="description2">
              <el-input
                type="textarea"
                placeholder="请输入商品描述2"
                v-model="productForm.description2"
                :rows="3">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <div class="form-buttons">
              <el-button @click="resetForm">重置</el-button>
              <el-button
                type="primary"
                @click="saveProduct"
                :loading="saving">
                保存商品
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单引用
const productFormRef = ref(null)

// 上传状态
const uploading = ref(false)
const saving = ref(false)

// 上传配置
const uploadUrl = `${BASE_URL}/api/files/upload`
const uploadHeaders = {
  // 如果需要认证token，可以在这里添加
  // 'Authorization': 'Bearer ' + localStorage.getItem('token')
}

// 表单数据
const productForm = reactive({
  productId: '',
  productName: '',
  pointsRequired: 0,
  description1: '',
  description2: '',
  imageUrl: '',
  quantity: 0,
  createdAt: ''
})

// 表单验证规则
const formRules = {
  productName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  pointsRequired: [
    { required: true, message: '请输入所需积分', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入库存数量', trigger: 'change' }
  ]
}

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }

  uploading.value = true
  return true
}

// 图片上传成功处理
const handleImageSuccess = (response, uploadFile) => {
  uploading.value = false
  if (response.state === 2001) {
    // 将返回的URL转换为/static/imgs/products/格式
    const originalUrl = response.data.url
    if (originalUrl && (originalUrl.includes('/imgs/products/') || originalUrl.startsWith('/imgs/products/'))) {
      // 将 /imgs/products/ 替换为 /static/imgs/products/
      productForm.imageUrl = originalUrl.replace('/imgs/products/', '/static/imgs/products/')
    } else {
      productForm.imageUrl = originalUrl
    }
    ElMessage.success('图片上传成功')
  } else {
    ElMessage.error(response.msg || '图片上传失败')
  }
}

// 图片上传失败处理
const handleImageError = (error) => {
  uploading.value = false
  ElMessage.error('图片上传失败: ' + error.message)
}

// 保存商品
const saveProduct = () => {
  if (!productFormRef.value) return

  productFormRef.value.validate((valid) => {
    if (valid) {
      saving.value = true

      axios.post(BASE_URL + '/api/products/add', productForm)
        .then((response) => {
          if (response.data.state === 2001) {
            ElMessage.success('商品添加成功！')
            ElMessageBox.confirm(
              '商品添加成功，是否继续添加新商品？',
              '操作成功',
              {
                confirmButtonText: '继续添加',
                cancelButtonText: '返回列表',
                type: 'success',
              }
            )
            .then(() => {
              resetForm()
            })
            .catch(() => {
              goBack()
            })
          } else {
            ElMessage.error(response.data.msg)
          }
        })
        .catch((error) => {
          ElMessage.error('保存失败：' + error.message)
        })
        .finally(() => {
          saving.value = false
        })
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(productForm, {
    productId: '',
    productName: '',
    pointsRequired: 0,
    description1: '',
    description2: '',
    imageUrl: '',
    quantity: 0,
    createdAt: ''
  })
  if (productFormRef.value) {
    productFormRef.value.resetFields()
  }
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 处理图片URL，确保正确的路径
const getImageUrl = (imageUrl) => {
  // 如果是/static/imgs/products/路径，映射到实际的/imgs/products/路径
  if (imageUrl && (imageUrl.includes('/static/imgs/products/') || imageUrl.startsWith('/static/imgs/products/'))) {
    return imageUrl.replace('/static/imgs/products/', '/imgs/products/');
  }
  // 其他情况直接返回
  return imageUrl || '';
}
</script>

<style scoped>
.product-add-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 添加面包屑导航样式 */
.el-breadcrumb {
  margin-bottom: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding: 16px 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-form {
  padding: 20px;
}

.product-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.product-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.product-uploader {
  width: 100%;
  display: block;
}

.product-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100%;
  height: 178px;
}

.product-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.product-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.product-image-preview {
  width: 100%;
  height: 178px;
  object-fit: cover;
  display: block;
}

.upload-text {
  position: absolute;
  bottom: 10px;
  width: 100%;
  text-align: center;
  color: #909399;
  font-size: 12px;
}

.image-url-display {
  margin-top: 10px;
}

.image-url-input {
  width: 100%;
}

.form-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

:deep(.el-input__inner) {
  border-radius: 6px;
}
</style>
